﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;

namespace NInjectTest
{
  public class DataLayer : IDataLayer
  {
    private static ISession session;
    
    public DataLayer(Configuration config)
    {
      if (config != null)
      {
        ISessionFactory sessionFactory = config.BuildSessionFactory();
        session = sessionFactory.OpenSession();
      }
    }

    public T Get<T, R>(R identifier)
    {
      try
      {
        return (T)session.Load<T>(identifier);
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public List<T> GetList<T>()
    {
      try
      {
        IQuery query = session.CreateQuery("from " + typeof(T).Name);
        ICollection<T> list = query.List<T>();
        return list.ToList<T>();
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public void Post<T>(T graph)
    {
      if (graph == null) return;

      try
      {
        ITransaction tx = session.BeginTransaction();

        if (session.GetIdentifier(graph) != null)
        {
          session.Save(graph);
        }
        else
        {
          session.Update(graph);
        }

        tx.Commit();
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public void PostList<T>(List<T> graphs)
    {
      if (graphs == null) return;
      
      try
      {
        ITransaction tx = session.BeginTransaction();
        
        foreach (T graph in graphs)
        {
          if (session.GetIdentifier(graph) != null)
          {
            session.Save(graph);
          }
          else
          {
            session.Update(graph);
          }
        }

        tx.Commit();
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
  }
}
